package com.leyou.controller;

import com.leyou.exception.LyException;
import com.leyou.UserDTO;
import com.leyou.pojo.User;
import com.leyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 验证手机号或者用户名是否唯一
     */
    @PostMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserNameOrPhone(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        Boolean result = userService.checkUserNameOrPhone(data, type);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> getCheckCode(@RequestParam("phone") String phone) {
        userService.getCheckCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping("/register")
    public ResponseEntity<User> register(@Valid User user, BindingResult result, String code) {
        if (result.hasErrors()) {
            String errorMsg = result.getFieldErrors().
                    stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(500, errorMsg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("/query")
    public ResponseEntity<UserDTO> findUserNameAndPassword(
            @RequestParam("username") String username
            , @RequestParam("password") String password) {
        UserDTO userDTO = userService.findUserNameAndPassword(username, password);
        return ResponseEntity.ok(userDTO);
    }


}
